import { DataNode, initNewNode } from './data';
import { ElementType } from './config';

// 添加节点
export function addNode(params) {
  const { info, prev } = params;
  const next = DataNode.DataNodeMap.get(prev.out);
  // 创建节点
  const current = initNewNode(info, next);
  // 添加节点
  const parent = prev.type === ElementType.BRANCH ? prev : prev.getParent();
  if (parent === prev) {
    parent?.insertChild(current, 0);
  } else {
    parent?.insertAfter(current, prev);
  }
  // 处理节点入口
  connectNodes({ node: prev, next: current, current: current });
  // 处理节点出口
  connectNodes({ node: current, next: next, current: current });
}

// 删除节点
export function deleteNode(params) {
  const { current } = params;
  const prev = DataNode.DataNodeMap.get(current.in);
  const next = DataNode.DataNodeMap.get(current.out);
  // 删除节点
  current.delete();
  // 处理节点出口
  connectNodes({ node: prev, next: next, current: current });
}

// 处理节点关系：设置node的out, next的in
function connectNodes(params) {
  const { node, next, current } = params;
  // out
  node.out = next.key;
  // in
  if (current.type === ElementType.BRANCH) {
    next.in = current.getParent()?.key;
  } else {
    if (node.type === ElementType.BRANCH) {
      next.in = node.getParent()?.key;
    } else {
      next.in = node.key;
    }
  }
} 